'''

将所有股票的历史数据下载到本地, 共有3个参数: 

参数列表
    stock_code 股票代码, 格式为股市类型.股票编码, 如 'sh.603300'

    start_date 开始日期, 格式为 %Y-%m-%d, 如 '2024-01-01', 默认值为'2024-01-01'

    end_date 结束日期, 格式为 %Y-%m-%d, 如 '2024-12-31', 默认值为 None

    forced=False 是否强制写文件，如果保存的文件已存在，且forced为True时，会强制写入。

返回值
    无，文件会被保存在 f'./data/{stock_code}.csv', 如 ./data/600749.csv。
    
使用示例
    download_stock(stock_code, '2000-01-01')  # 下载华铁应急

【参考资料】
1. 技术文档地址: https://ai-cyber-security.feishu.cn/docx/AB1fdqV9xo9K9axwT3hcMOOcnzc
2. BaoStock官网: http://baostock.com/baostock/index.php/Python_API文档

'''
import os, sys
import baostock as bs
from datetime import datetime, timedelta
import pandas as pd
from utils.common import *


df = pd.read_csv('./samples/sh.600749.csv', index_col=0)
#print(df)

# 买入：每掉5%，补仓10%, 仓位： [0.9, ]
# 卖出：上涨10%的单子就卖出

ps1 = [ 1.0 - p * 0.1 for p in range(11)]
ps2 = [1.0 - p * 0.05 for p in range(11)]
#print('ps1:', ps1)
#print('ps2:', ps2)



df1 = pd.DataFrame({
    "price": [10.5, 10.0, 9.5],
    "count": [5000, 5000, 5000],
    })


ops = [(10.5, 5000),
       (10.0, 5000),
       (9.5, 5000) ]

history = [('2024-01-01', 10.50, '2024-03-15', 11.50, 5000)]

history = {
    'date1': ['2024-01-01'], 
    'price1': [10.50],
    'date1': ['2024-03-26'], 
    'price2': [10.50],
    'count': [5000],
}


df2 = pd.DataFrame({
    "price": [10.5, 10.0, 9.5],
    "count": [5000, 5000, 5000],
    })

in_price = 10.00
out_price = 12.00

#cur_price = df.iloc[0].iloc[4]
#print('current price:', cur_price)
start_money = 1.0
rest_money = 1.0

money_pool = 1.0
stock_pool = 1.0

actual_count = 0
all_cost = 0

in_prices=[0]
in_counts=[0]


for i in range(len(df)):
    rowi = df.iloc[i]
    date1 = rowi.iloc[0]         # 身份证号
    price1 = rowi.iloc[1]        # 身份证号
    date2 = rowi.iloc[2]         # 姓名
    price2 = rowi.iloc[3]        # 民族
    count = rowi.iloc[4]         # 培养层次
    date, pprice, high, low, cprice = rowi
    #print(f'{date}, {pprice:.2f}, {high:.2f}, {low:.2f}, {cprice:.2f}')

    #print(f'low: {low}, in_price: {in_price}')
    if low > in_price:
        continue

    level = int((low / in_price - 0.5) / 0.05)
    #print('level:', level)

    expected_money_usage = level * 0.1
    if expected_money_usage >= rest_money:
        continue
    buy_price = (0.5 + 0.05 * level) * in_price
    rest_money -= 0.1
    buy_count = 0.1 / buy_price
    in_prices.append(buy_price)
    in_counts.append(buy_count)
    actual_count += buy_count
    in_cost = sum(in_prices)/sum(in_counts) if len(in_counts) > 0 else 0

    print(f'expected_money_usage: {expected_money_usage:.2f},   rest money: {rest_money:.4f}, buy price: {buy_price:.2f}')
    #print(f'{date}    high: {high:5.2f},  low: {low:5.2f},   level: {level}, actual_count: {actual_count}, rest: {rest_money}')
#    break


